package models;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;


import play.db.jpa.Model;

/**
 * Represent category in application i.e. book, CD, movie. Contains basic set of
 * custom fields that all {@link Item|items} in this category must has.
 * 
 * @author koziolek
 * 
 */
@Entity
public class Category extends Model {

	/**
	 * Name of the category.
	 */
	private String name;

	/**
	 * List of {@link CustomField|custom fields} that all items in this category
	 * must has.
	 */
	@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE,
			CascadeType.REFRESH })
	@JoinTable(name = "category_keys", 
			joinColumns = @JoinColumn(name = "cid"), 
			inverseJoinColumns = @JoinColumn(name = "kid")
		)
	private Set<Key> categoryKeys;

	public Category(String name) {
		super();
		this.name = name;
		this.categoryKeys = new HashSet<Key>();
	}

	public Category(String name, Set<Key> categoryKeys) {
		super();
		this.name = name;
		this.categoryKeys = categoryKeys;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set<Key> getCategoryKeys() {
		return categoryKeys;
	}

	public void setCategoryKeys(Set<Key> categoryKeys) {
		this.categoryKeys = categoryKeys;
	}

	public void setCategoryKey(Key key) {
		if (!this.contains(key)) {
			this.categoryKeys.add(key);
		}
	}

	private boolean contains(Key key) {
		if (key == null)
			return false;
		for (Key k : categoryKeys) {
			if (k.equals(key)) {
				return true;
			}
		}
		return false;
	}

}
